﻿
using Newtonsoft.Json;
using RestSharp;
using SMALLERP.DataClass;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using XJLSC.ComClass;
using XJLSC.DataClass;

namespace XJLSC.Sy
{
    public partial class LTKJK : Form
    {
        private SqlDataReader sdr1;
        private readonly DataBase db = new DataBase();
        public delegate void Cdgzzx(object sender, EventArgs e);
        //定义委托对象
        public Cdgzzx cdgzzx;
        private readonly object DESencrypt;
        static SqlDependency dependency;

        public LTKJK()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                SqlDependency.Start(db.connectionString1);//传入连接字符串,启动基于数据库的监听
                UpdateGrid(db.connectionString1);
                textBox4.Text = "运行中";
                textBox4.ForeColor = Color.Green;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "软件提示");
                throw ex;
            }

            //String url = "http://192.168.88.252/ERP/Sunrise.WarehouseManagement.Service.asmx";
            //String soapAction = "http://183.134.214.229/BillsInOut";
            //var soapClient = new SoapClient(url, soapAction);
            //soapClient.Arguments.Add(new SoapParameter("requestXml", "{'Head': { 'MethodCode': 'M1001', 'Security': { 'Token': ''}},'Body': { 'ERP_ID': 'ca0a9a91-bb13-4717-8590-d9258f5c292f'}}"));
            //Object ob = soapClient.GetResult();
           
        }

        private static void UpdateGrid(String connectionString)
        {
            String strSql = "";
            DataBase db = new DataBase();
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                //对被监控的目标表做简单查询，此处 要注意 不能使用* 表名要加[dbo] 否则会出现一直调用执行 OnChange
                using (SqlCommand command = new SqlCommand("SELECT ERP_ID,BILLS_TYPE,TASK_EMPL_CODE,DEPT_CODE FROM [dbo].[E10_WMS_TRANSLOG] WHERE DO_Y='N'", connection))
                {
                    connection.Open();
                    command.CommandType = CommandType.Text;
                    dependency = new SqlDependency(command);
                    command.ExecuteNonQuery();
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);//添加监控，检测数据表变化
                    using (SqlDataReader sdr = command.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            int bs = 0;
                            using (SqlConnection connection0 = new SqlConnection(connectionString))
                            {
                                using (SqlCommand command0 = new SqlCommand("SELECT COUNT(*) MCOUNT FROM TRANSACTION_LINE A LEFT JOIN ITEM B ON A.ITEM_ID=B.ITEM_BUSINESS_ID LEFT JOIN ITEM_LOT C ON B.ITEM_BUSINESS_ID=C.ITEM_ID AND A.ITEM_LOT_ID=C.ITEM_LOT_ID LEFT JOIN UNIT D ON D.UNIT_ID=B.STOCK_UNIT_ID LEFT JOIN ITEM_PLANT E ON E.ITEM_ID=A.ITEM_ID WHERE A.DOC_NO = '" + sdr["ERP_ID"].ToString() + "' AND E.ISSUE_CRITICAL = '1'", connection0))
                                {
                                    
                                    connection0.Open();
                                    command0.CommandType = CommandType.Text;
                                    command0.ExecuteNonQuery();
                                    using (SqlDataReader sdr0 = command0.ExecuteReader())
                                    {
                                        while (sdr0.Read())
                                        {
                                            bs = Convert.ToInt16(sdr0["MCOUNT"].ToString());
                                        }
                                        sdr0.Close();
                                    }
                                }
                            }

                           
                            Hashtable ht = new Hashtable();
                            ht.Add("ERP_ID", sdr["ERP_ID"].ToString());
                            ht.Add("BILLS_TYPE", sdr["BILLS_TYPE"].ToString());
                            ht.Add("TASK_EMPL_CODE", sdr["TASK_EMPL_CODE"].ToString());
                            ht.Add("DEPT_CODE", sdr["DEPT_CODE"].ToString());
                         
                            BillsMate[] MATES = new BillsMate[bs];
                            using (SqlConnection connection1 = new SqlConnection(connectionString))
                            {
                                using (SqlCommand command1 = new SqlCommand("SELECT B.ITEM_CODE,'A' ZH,ITEM_NAME,B.ITEM_SPECIFICATION,B.ITEM_DESC,CAST(INVENTORY_QTY AS numeric(18,2)) INVENTORY_QTY,ISNULL(C.LOT_CODE,'********************') LOT_NO,ISNULL(D.UNIT_CODE,'') UNIT_CODE FROM TRANSACTION_LINE A LEFT JOIN ITEM B ON A.ITEM_ID=B.ITEM_BUSINESS_ID LEFT JOIN ITEM_LOT C ON B.ITEM_BUSINESS_ID=C.ITEM_ID AND A.ITEM_LOT_ID=C.ITEM_LOT_ID LEFT JOIN UNIT D ON D.UNIT_ID=B.STOCK_UNIT_ID LEFT JOIN ITEM_PLANT E ON E.ITEM_ID=A.ITEM_ID WHERE DOC_NO='" + sdr["ERP_ID"].ToString() + "' AND E.ISSUE_CRITICAL='1'", connection1))
                                {
                                    connection1.Open();
                                    command1.CommandType = CommandType.Text;
                                    command1.ExecuteNonQuery();
                                    using (SqlDataReader sdr1 = command1.ExecuteReader())
                                    {
                                        int i = 0;
                                        while (sdr1.Read())
                                        {
                                            BillsMate ma = new BillsMate();
                                            ma.MAT_CODE = sdr1["ITEM_CODE"].ToString();
                                            ma.PO_CODE = sdr1["ZH"].ToString();
                                            ma.MAT_NAME = sdr1["ITEM_NAME"].ToString();
                                            ma.MAT_SPED = sdr1["ITEM_SPECIFICATION"].ToString();
                                            ma.MAT_MODEL = sdr1["ITEM_DESC"].ToString();
                                            ma.MAT_COUNT = Convert.ToDouble(sdr1["INVENTORY_QTY"].ToString());
                                            ma.MAT_BATCH_ID = sdr1["LOT_NO"].ToString();
                                            ma.MAT_UNIT = sdr1["UNIT_CODE"].ToString();
                                            MATES[i] = ma;
                                            i += 1;
                                        }

                                        sdr1.Close();
                                    }
                                }
                            }
                            ht.Add("MATES", MATES);

                            XmlDocument xx = WebSvcCaller.QuerySoapWebService("http://192.168.88.252/ERP/Sunrise.WarehouseManagement.Service.asmx", "BillsInOut", ht);

                            //WebResponse response = WebSvcCaller.QuerySoapWebService("http://192.168.88.252/ERP/Sunrise.WarehouseManagement.Service.asmx", "BillsInOut", ht);
                            //Stream myResponseStream = response.GetResponseStream();
                            ////获取响应内容
                            //string retString = string.Empty;

                            //using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.Unicode))
                            //{
                            //    retString = myStreamReader.ReadToEnd();
                            //}
                            //myResponseStream.Close();
                            //String xmlStr = xx.InnerXml;
                            //MessageBox.Show(retString.ToString(), "xml");
                            //string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xx);
                            //MessageBox.Show(json, "json");
                            StringBuilder sb = new StringBuilder();
                            StringWriter sw = new StringWriter(sb);
                            XmlTextWriter writer = new XmlTextWriter(sw);
                            writer.Formatting = System.Xml.Formatting.Indented;
                            writer.Indentation = 4;
                            writer.IndentChar = ' ';
                            xx.WriteContentTo(writer);

                            //XmlDocument document = new XmlDocument();
                            //document.LoadXml(sb.ToString());

                            //MessageBox.Show(document.InnerXml.ToString(), "xml");

                            //XmlNodeList nodelist = xx.SelectNodes("/Feedback");
                            //MessageBox.Show(nodelist.Count.ToString(), "node");
                            //foreach (XmlNode node in nodelist)
                            //{
                            //    MessageBox.Show(node.Value.ToString(), "node");
                            //    if (node.Attributes["e_msgty"] != null)
                            //    {
                            //        string name = node.Attributes["e_msgty"].Value;
                            //        MessageBox.Show(name.ToString(), "1");
                            //    }
                            //}




                            //var data = HttpHelper.SoapV1_2WebService("http://192.168.88.252/ERP/Sunrise.WarehouseManagement.Service.asmx", "BillsInOut", ht, "http://183.134.214.229/");
                            //MessageBox.Show(data.ToString(), "123");

                            //XmlDocument data = HttpHelper.HashtableToSoap12(ht, "http://183.134.214.229/", "BillsInOut");
                            //StringBuilder sb = new StringBuilder();
                            //StringWriter sw = new StringWriter(sb);
                            //XmlTextWriter writer = new XmlTextWriter(sw);
                            //writer.Formatting = Formatting.Indented;
                            //writer.Indentation = 4;
                            //writer.IndentChar = ' ';
                            //data.WriteContentTo(writer);                        
                            //MessageBox.Show(sb.ToString(), "1");
                            ////foreach(DictionaryEntry item in ht)
                            // {
                            //     MessageBox.Show(item.Key+":"+item.Value);
                            // }
                            //if (sucess)
                            //{
                            //if (sdr["MA005"].ToString().Trim() == "请购单")
                            //{
                            //    strSql = "UPDATE REQUISITION SET EFNETDOCNumber='" + processInstanceId + "' WHERE REQUISITION_ID='" + sdr["MA002"].ToString() + "'";
                            //}
                            //else
                            //{
                            //    strSql = "UPDATE REQUISITION SET EFNETDOCNumber='" + processInstanceId + "' WHERE REQUISITION_ID='" + sdr["MA002"].ToString() + "'";
                            //}
                            //try
                            //{
                            //    if (db.ExecDataBySql1(strSql) > 0)
                            //    {
                            //    }
                            //    else
                            //    {
                            //    }
                            //}
                            //catch (Exception ex)
                            //{
                            //    MessageBox.Show(ex.Message, "软件提示");
                            //    throw ex;
                            //}

                            strSql = "UPDATE E10_WMS_TRANSLOG SET DO_Y='Y',DO_TIME=CONVERT(CHAR(20),GETDATE(),120),RMARK='" + sb.ToString() + "' WHERE ERP_ID='" + sdr["ERP_ID"].ToString() + "'";
                                try
                                {
                                    if (db.ExecDataBySql1(strSql) > 0)
                                    {
                                    }
                                    else
                                    {
                                    }
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message, "软件提示");
                                    throw ex;
                                }
                            //}
                        }
                        sdr.Close();
                    }                                                                    //必须要执行一下command
                }
            }
        }

        



        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            DataBase db = new DataBase();
            SqlDependency dependency = sender as SqlDependency;
            dependency.OnChange -= dependency_OnChange;
            if (e.Info != SqlNotificationInfo.Invalid)
            {
                UpdateGrid(db.connectionString1);//此处需重复注册<span style="font-family: Arial, Helvetica, sans-serif;">SqlDependency，每次注册只执行一次，SqlDependency.id可用用于验证注册唯一 编号
            }
        }

        private static void dependency1_OnChange(object sender, SqlNotificationEventArgs e)
        {
            DataBase db = new DataBase();
            SqlDependency dependency = sender as SqlDependency;
            dependency.OnChange -= dependency_OnChange;
            if (e.Info != SqlNotificationInfo.Invalid)
            {
                UpdateGrid1(db.connectionString1);//此处需重复注册<span style="font-family: Arial, Helvetica, sans-serif;">SqlDependency，每次注册只执行一次，SqlDependency.id可用用于验证注册唯一 编号
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = "等待中";
            textBox1.ForeColor = Color.Red;
            textBox4.Text = "等待中";
            textBox4.ForeColor = Color.Red;
            SqlDependency.Stop(db.connectionString1);//传入连接字符串,启动基于数据库的监听
        }

        private void LTKJK_Load(object sender, EventArgs e)
        {
            textBox4.Text = "等待中";
            textBox4.ForeColor = Color.Red;
            textBox1.Text = "等待中";
            textBox1.ForeColor = Color.Red;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {

                SqlDependency.Start(db.connectionString1);//传入连接字符串,启动基于数据库的监听
                UpdateGrid1(db.connectionString1);
                textBox1.Text = "运行中";
                textBox1.ForeColor = Color.Green;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "软件提示");
                throw ex;
            }
        }
        private static void UpdateGrid1(String connectionString)
        {
            String strSql = "";
            DataBase db = new DataBase();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                //对被监控的目标表做简单查询，此处 要注意 不能使用* 表名要加[dbo] 否则会出现一直调用执行 OnChange
                using (SqlCommand command = new SqlCommand("SELECT MA001,MA002,MA003,MA005 FROM [dbo].[EFSMA] WHERE MA004='N'", connection))
                {
                    connection.Open();
                    command.CommandType = CommandType.Text;
                    dependency = new SqlDependency(command);
                    command.ExecuteNonQuery();

                    
                    dependency.OnChange += new OnChangeEventHandler(dependency1_OnChange);//添加监控，检测数据表变化
                    using (SqlDataReader sdr = command.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            var client = new RestClient("http://192.168.88.251:8080/REQUISITIONApprove?djid=" + sdr["MA002"].ToString() + "&creator=" + sdr["MA003"].ToString() + "");
                            //var client = new RestClient("http://192.168.88.251:8080/REQUISITIONApprove?djid=d41918d2-0899-4cfa-1D91-18F83C64DFF8&creator=68E86F12-C4A0-43F3-67F3-18D960653917");
                            client.Timeout = -1;
                            var request = new RestRequest(Method.GET);
                            IRestResponse response = client.Execute(request);
                            spresponse attach = JsonConvert.DeserializeObject<spresponse>(response.Content.ToString());
                            String processInstanceId = attach.data.processInstanceId;
                            String sucess = attach.success;
                            if (sucess == "true")
                            {
                                if (sdr["MA005"].ToString().Trim() == "请购单")
                                {
                                    strSql = "UPDATE REQUISITION SET EFNETDOCNumber='" + processInstanceId + "' WHERE REQUISITION_ID='" + sdr["MA002"].ToString() + "'";
                                }
                                else
                                {
                                    strSql = "UPDATE REQUISITION SET EFNETDOCNumber='" + processInstanceId + "' WHERE REQUISITION_ID='" + sdr["MA002"].ToString() + "'";
                                }
                                try
                                {
                                    if (db.ExecDataBySql1(strSql) > 0)
                                    {
                                    }
                                    else
                                    {
                                    }
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message, "软件提示");
                                    throw ex;
                                }

                                strSql = "UPDATE EFSMA SET MA004='Y',MA001='" + processInstanceId + "',MA006=CONVERT(CHAR(20),GETDATE(),120) WHERE MA002='" + sdr["MA002"].ToString() + "'";
                                try
                                {
                                    if (db.ExecDataBySql1(strSql) > 0)
                                    {
                                    }
                                    else
                                    {
                                    }
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message, "软件提示");
                                    throw ex;
                                }
                            }
                        }
                        sdr.Close();
                    }                                                                    //必须要执行一下command
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Text = "等待中";
            textBox1.ForeColor = Color.Red;
            textBox4.Text = "等待中";
            textBox4.ForeColor = Color.Red;
            SqlDependency.Stop(db.connectionString1);//传入连接字符串,启动基于数据库的监听
        }
    }
}
